package com.bob.light.activity

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.text.TextWatcher
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.bob.light.*
import com.bob.light.config.AppConfig
import kotlinx.android.synthetic.main.app_activity_register.*

class RegisterActivity : AppCompatActivity() {

    private val mEtToWatcherMap = hashMapOf<EditText, TextWatcher>()
    private val mSendCodeBtnState = MutableLiveData<Boolean>()
    private val mRegisterBtnState = MutableLiveData<Boolean>()

    companion object {

        @JvmStatic
        fun navigation(activity: AppCompatActivity?) {
            activity?.let { context ->
                val intent = Intent(context, RegisterActivity::class.java)
                context.startActivityForResult(intent, REQUEST_CODE)
            }
        }

        const val REQUEST_CODE = 0x0000f001
        const val RESULT_CODE = 0x00000001
        const val PHONE_NUMBER = "phoneNumber"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.app_activity_register)
        initView()
    }

    private fun initView() {
        registerEditTextWatcher(et_phone, isPhoneEt = true)
        registerEditTextWatcher(et_pwn)
        registerEditTextWatcher(et_code)
        observeCodeClickListener()
        observeRegisterBtn()
        observeKeyDown()
    }

    /**
     * @param editText 输入框的监听
     */
    private fun registerEditTextWatcher(editText: EditText?, isPhoneEt: Boolean = false) {
        if (isPhoneEt) {
            et_phone?.setOnFormatMobileEditTextListener {
                mSendCodeBtnState.value = ((et_phone?.isLegalMobile) == true)
            }
        }
        editText?.addTextChangedSampleListener {
            val isLegalMobile = (et_phone?.isLegalMobile)?:false
            val pwd = (et_pwn?.text?.toString())?:""
            val code = (et_code?.text?.toString())?:""
            mRegisterBtnState.value = (isLegalMobile && (!TextUtils.isEmpty(pwd)) && (!TextUtils.isEmpty(code)))
        }?.let { newWatcher ->
            val watcher = mEtToWatcherMap[editText]
            if (watcher != null) {
                editText.removeTextChangedListener(watcher)
            }
            mEtToWatcherMap[editText] = newWatcher
        }
    }

    /**
     * @desc 对验证码控件的状态监听 与 点击事件
     */
    private fun observeCodeClickListener() {
        tv_send_code?.isEnabled = false
        mSendCodeBtnState.observe(this@RegisterActivity, Observer { isEnabled ->
            tv_send_code?.isEnabled = isEnabled
        })
        tv_send_code?.setOnSingleClickListener {
            executeCountdown()
            val phone = (et_phone?.mobile)?:""
            sendCode(phone)
        }
    }

    /**
     * @desc 倒计时
     */
    private fun executeCountdown(countDown: Int = 60) {
        if (countDown > 0) {
            val text = "$countDown ${getString(R.string.app_second)}"
            tv_send_code?.text = text
        } else {
            tv_send_code?.text = getString(R.string.app_login_send_code)
        }
        tv_send_code?.postDelayed({
            if (countDown <= 0 || this@RegisterActivity.isFinishing) {
                return@postDelayed
            }
            executeCountdown(countDown - 1)
        }, 1000L)
    }

    /**
     * @desc 发送短信验证码
     */
    private fun sendCode(phone: String) {
        if (TextUtils.isEmpty(phone)) {
            return
        }
        TuyaHomeSDKHelper.sendVerifyCodeWithPhoneInChina(phone,
                successCallback = {
                    "验证码发送成功".toast()
                }, failCallback = {
            "验证码发送失败".toast()
        })
    }

    private fun observeRegisterBtn() {
        app_activity_register_btn?.isEnabled = false
        mRegisterBtnState.observe(this@RegisterActivity, Observer { isEnabled ->
            app_activity_register_btn?.isEnabled = isEnabled
        })
        app_activity_register_btn?.setOnSingleClickListener {
            val phone = (et_phone?.mobile)?:""
            val pwd = (et_pwn?.text?.toString())?:""
            val code = (et_code?.text?.toString())?:""
            executeRegister(phone, pwd, code)
        }
    }

    private fun executeRegister(phone: String, pwd: String, code: String) {
        val isLegalMobile = (et_phone?.isLegalMobile)?:false
        if (!isLegalMobile || TextUtils.isEmpty(pwd) || TextUtils.isEmpty(code)) {
            return
        }
        TuyaHomeSDKHelper.registerAccountWithPhoneInChina(phone, pwd, code,
                successCallback = {
                    AppConfig.builder().isFirstRegister(true).build()
                    val intent = Intent()
                    intent.putExtra(PHONE_NUMBER, phone)
                    setResult(RESULT_CODE, intent)
                    finish()
                }, failCallback = {
                   "注册失败".toast()
                })
    }

    private fun observeKeyDown() {
        fl_back_pressed?.setOnSingleClickListener {
            finish()
        }
    }

    override fun onDestroy() {
        mEtToWatcherMap.mapKeys {
            it.key.removeTextChangedListener(it.value)
        }
        super.onDestroy()
    }

}